# 220204 1110

# 从已有的数组创建数组

import numpy as np

# numpy.asarray
# numpy.asarray(a, dtype = None, order = None)

l10 = [1, 2, 3]
a11 = np.asarray(l10)
print(type(l10)) # <class 'list'>
print(type(a11)) # <class 'numpy.ndarray'>
print('l10=', l10)
print('a11=', a11)

t17 = 1,2,3
a19 = np.asarray(t17)
print(type(t17)) # <class 'tuple'>
print(type(a19))

print('t17=', t17)
print('a19=', a19)

l25 = [(1,2,3),(4,5)]
a26 = np.asarray(l25)
print(type(l25))
print(type(a26))
print('l25=', l25)
print('a26=', a26, ', shape=', a26.shape, ', ndim=', a26.ndim) # shape= (2,) , ndim= 1

a32 = np.asarray(l10, dtype=float)
print(type(a32))
print('a32=', a32)

print('end.1')

# numpy.frombuffer
# 用于实现动态数组
# 接受 buffer 输入参数，以流的形式读入转化成 ndarray 对象
# numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

# buffer 是字符串的时候，Python3 默认 str 是 Unicode 类型，所以要转成 bytestring 在原 str 前加上 b
# s43 = 'Hello, world' # TypeError: a bytes-like object is required, not 'str'
s43 = b'Hello, world' # right
a44 = np.frombuffer(s43, dtype='S1')
print('a44=', a44) #  [b'H' b'e' b'l' b'l' b'o' b',' b' ' b'w' b'o' b'r' b'l' b'd']

print('end.2')

# numpy.fromiter
# 从可迭代对象中建立 ndarray 对象，返回一维数组
# numpy.fromiter(iterable, dtype, count=-1)

l55 = range(5)
it56 = iter(l55)
print(type(it56)) # <class 'range_iterator'>
a58 = np.fromiter(it56, dtype=float)
print(type(a58))
print('a58=', a58)

print('end.3')

# 从数值范围创建数组
# numpy.arange
# numpy.linspace
# numpy.logspace

# numpy.arange(start, stop, step, dtype)

a71 = np.arange(5)
print('a71=', a71)

a74 = np.arange(5, 10, dtype=float)
print('a74=', a74)

# np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
# 创建一个一维数组，数组是一个等差数列构成的

a80 = np.linspace(1,10,10)
print('a80=', a80)
a82 = np.linspace(1,1,10) # 元素全部是1的等差数列
print('a82=', a82)
a84 = np.linspace(10,20,5, endpoint=False)
print('a84=', a84)
a86 = np.linspace(10,20,50, endpoint=False)
print('a86=', a86) # 出现小数了  [10.  10.2 10.4 10.6 10.8 11. ...]

a89 = np.linspace(1,10,10, retstep=True)
print(type(a86)) # <class 'numpy.ndarray'>
print(type(a89)) # <class 'tuple'>
print('a89=', a89) # (array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]), 1.0)

a94 = np.linspace(1,10,10).reshape((10,1))
print(type(a94))
print('a94=', a94)

# np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
# 用于创建一个于等比数列

a101 = np.logspace(1, 2, num=10)
print(type(a101))
print('a101=', a101)

a105 = np.logspace(1, 2) # num默认为 50
print('a105=', a105)

# 将对数的底数设置为 2
a109 = np.logspace(0, 9, 10, base=2)
print('a109=', a109)

print('end.4')